//
//  LSZDownloadVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2017/10/18.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LSZDownloadVC.h"
#import "LCHistoryDataManager.h"
#import "JKSongsMessStatus.h"

@interface LSZDownloadVC ()

@end

@implementation LSZDownloadVC

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [LCFloatingWindow sharedInstance].hidden = YES;
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [LCFloatingWindow sharedInstance].hidden = NO;//下面的音乐播放不隐藏
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationPraisePoetry:) name:@"PUSHPLAYPAGE" object:nil];
    [self setBarUI];
    [self.tableViewDownload registerClass:[LSZRandombroadcastHeaderCell class] forHeaderFooterViewReuseIdentifier:@"LSZRandombroadcastHeaderCell"];
    [self.tableViewDownload registerClass:[LSZDownloadCell class] forCellReuseIdentifier:@"LSZDownloadCell"];
}
///跳转到播放页
-(void)receiveNotificationPraisePoetry:(NSNotification *)notification{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"LCPlayStoryboard" bundle:nil];
    UIViewController *controller = [sb instantiateInitialViewController];
    [self presentViewController:controller animated:YES completion:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _LCPlayer.downloadData.count;//已下载
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (_LCPlayer.downloadData.count >8) {
        return 60;
    }else{
        return 0;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UITableViewHeaderFooterView * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!cell) {
        cell = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"foot"];
    }
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LSZRandombroadcastHeaderCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSZRandombroadcastHeaderCell"];
    UITapGestureRecognizer * singleTapimageView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickPlay)];
    [cell.imageViewPlay addGestureRecognizer:singleTapimageView];
    
    UITapGestureRecognizer * singleTaplabel = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickPlay)];
    [cell.label addGestureRecognizer:singleTaplabel];
    [cell.butPaly addTarget:self action:@selector(clickPlay) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //这个是已完成的单元格
    LSZDownloadCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZDownloadCell" forIndexPath:indexPath];
    cell.labelNumber.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    cell.labelSong.text = [NSString stringWithFormat:@"%@", _LCPlayer.downloadData[indexPath.row][@"title"]];//@"歌曲的名字";
    if (_LCPlayer.downloadData[indexPath.row][@"album"]) {
        cell.labelAlbums.text = [NSString stringWithFormat:@"%@", _LCPlayer.downloadData[indexPath.row][@"album"]]; //@"专辑的名字";//singerName
    } else {//如果为空就显示空白
        cell.labelAlbums.text = @"";
    }
    cell.butDeleting.tag = indexPath.row+1;
    [cell.butDeleting addTarget:self action:@selector(clickDeletingCell:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
//}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [LSZSpecialPackaging addPlaylistWithArrayData:_LCPlayer.downloadData];
        LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
        _LCPlayer.songs = playlistTest.allSongs;
        if (_LCPlayer.songs != nil) {
            [_LCPlayer playAtIndex:indexPath.row isSelectPlay:YES];
        }
}

#pragma mark - 循环全部
-(void)clickPlay
{
    [LSZSpecialPackaging addPlaylistWithArrayData:_LCPlayer.downloadData];
    LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
    _LCPlayer.songs = playlistTest.allSongs;
    if (_LCPlayer.songs != nil) {
        [_LCPlayer playAtIndex:0 isSelectPlay:YES];
    }
}
#pragma mark - 删除某个已下载的歌曲
-(void)clickDeletingCell:(UIButton *)but
{
    //循环出来
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"DOWNLOADONGS"];
    //查出来model
    JKSongsMessStatus *song = array[(long)but.tag-1];
    NSDictionary *json = [song yy_modelToJSONObject];
    for (NSInteger i = 0; i < _LCPlayer.downloadData.count; i++) {
        NSDictionary *dict = _LCPlayer.downloadData[i];
        if ([json[@"title"] isEqualToString:dict[@"title"]]) {
            [_LCPlayer.downloadData removeObject:dict];
            [_LCPlayer.downloadData removeObject:dict];
            [self deleteFileWithFileName:dict[@"filePath"]];
        }
    }
    [[NSUserDefaults standardUserDefaults] setObject:_LCPlayer.downloadData.copy forKey:@"DOWNLOADONGS"];
    [self.tableViewDownload reloadData];
}
//根据路径删除
-(void)deleteFileWithFileName:(NSString *)fileName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document=[NSSearchPathForDirectoriesInDomains(13, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *folder = document;//[document stringByAppendingPathComponent:@"folder"];
    NSArray *fileList ;
    fileList =[fileManager contentsOfDirectoryAtPath:folder error:NULL];

    for (NSString *file in fileList) {
        if ([fileName hasSuffix:file]) {
//                NSLog(@"file=%@",file);
                NSString *path =[folder stringByAppendingPathComponent:file];
//                        NSLog(@"得到的路径=%@",path);
                BOOL blDele= [fileManager removeItemAtPath:path error:nil];
                if (blDele) {
//                    NSLog(@"dele success");
                }else {
//                    NSLog(@"dele fail");
                }
            }
    }
}

-(UITableView *)tableViewDownload
{
    if (_tableViewDownload ==nil) {
        _tableViewDownload = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-60) style:UITableViewStylePlain];
        _tableViewDownload.dataSource =self;
        _tableViewDownload.delegate =self;
        //添加以下代码关闭估算行高
        _tableViewDownload.estimatedRowHeight = 0;
        _tableViewDownload.estimatedSectionHeaderHeight = 0;
        _tableViewDownload.estimatedSectionFooterHeight = 0;
        _tableViewDownload.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        [self.view addSubview:_tableViewDownload];
    }
    return _tableViewDownload;
}
#pragma mark - 导航上的设置
-(void)setBarUI
{
     self.view.backgroundColor = RGBColor(236, 236, 236);
}
#pragma mark - 返回上一个界面
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
